package address

import (
	"errors"

	"gitee.com/coin-kit/btc-tx/txscript"
	"github.com/btcsuite/btcutil/base58"
)

type Address struct {
	script *txscript.Script
}

func FromWIFAddress(wif string, params *Params) (*Address, error) {
	hash, header, err := base58.CheckDecode(wif)
	if err != nil {
		return nil, err
	}
	if header == params.AddressHeader {
		script := txscript.DefaultP2PKHScript(hash)
		return &Address{script: script}, nil
	}
	if header == params.P2SHHeader {
		script := txscript.DefaultP2SHScript(hash)
		return &Address{script: script}, nil
	}
	return nil, errors.New("Unknown address protocol")
}

func (addr *Address) WIF(params *Params) string {
	if addr.script.IsP2PKH() == true {
		pkh := addr.script.GetOP(2).GetData()
		return base58.CheckEncode(pkh, params.AddressHeader)
	}
	if addr.script.IsP2SH() == true {
		sh := addr.script.GetOP(1).GetData()
		return base58.CheckEncode(sh, params.P2SHHeader)
	}
	return ""
}

func (addr *Address) IsP2PKH() bool {
	return addr.script.IsP2PKH()
}

func (addr *Address) IsP2SH() bool {
	return addr.script.IsP2SH()
}

func (addr *Address) ToPkScript() []byte {
	return addr.script.Bytes()
}
